package com.ebeitech.doorapp.view.setting;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.db.CommonDBHelper;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.domain.CommonItem;
import com.ebeitech.library.ui.CommonItemView;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.FileUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.VersionUtil;
import com.ebeitech.library.util.ViewUtil;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by alice on 2017/10/31.
 */
public class SettingSystemActivity extends BaseActivity {

	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.view_content)
	LinearLayout viewContent;
	CommonItemView clearCacheView;

	private List<CommonItem> mModules = new ArrayList<CommonItem>();

	@OnClick({R.id.btn_logout})
	void onClick(View view){
		switch (view.getId()) {
			case R.id.btn_logout: {
				onLogoutClick();
				break;
			}
		}
	}

	private Context mContext;
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			String name = v.getTag().toString();
			if ("数据导出".equals(name)) {
				onBackupClicked(v);
			} else if (getString(R.string.ebei_change_password).equals(name)) {
				startActivity(new Intent(mContext, ChangePasswordActivity.class));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_setting);
		mContext = this;
		ButterKnife.bind(this);
		initView();
	}

	private void initView() {
		mTitleBarView.setTitle(getString(R.string.ebei_setting_system));
		findViewById(R.id.view_top).setVisibility(View.GONE);
		findViewById(R.id.view_logout).setVisibility(View.VISIBLE);

		mModules.clear();
		CommonItem module = null;
		module = new CommonItem();
		module.setTitle(getString(R.string.ebei_clear_cache));
		module.setItemStyle(CommonItemView.ItemStyle.BUTTON);
		mModules.add(module);
		module = new CommonItem();
		module.setTitle(getString(R.string.ebei_change_password));
		module.setItemStyle(CommonItemView.ItemStyle.SELECT);
		mModules.add(module);

		for (int i = 0; i < mModules.size(); i++) {
			CommonItem item = mModules.get(i);
			String title = item.getTitle();
			CommonItemView itemView = new CommonItemView(mContext);
			itemView.setTitle(title);
			itemView.setTitleColor(getResources().getColor(R.color.ebei_black));
			itemView.setItemStyle(item.getItemStyle());
			itemView.setIsDividerViewVisible(false);
			viewContent.addView(itemView);
			itemView.setTag(title);

			if (getString(R.string.ebei_clear_cache).equals(title)) {
				clearCacheView = itemView;
			} else {
				itemView.setOnClickListener(mClickListener);
			}
		}

		new AsyncTask<Void, Void, Void>() {

			private long cache;

			@Override
			protected Void doInBackground(Void... voids) {
				String path = CommonUtil.getCacheFile(mContext);
				cache = FileUtil.getFileSize(path);
				path = CommonUtil.getExternalCacheFile(mContext);
				cache += FileUtil.getFileSize(path);
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				DecimalFormat df = new DecimalFormat("0.00");
				String cacheStr = df.format((double) cache / 1048576) + "MB";
				clearCacheView.setRightButtonTextView(cacheStr, null);
				clearCacheView.setRightButtonView("清理", new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						onClearCache();
					}
				});
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void onLogoutClick() {
		ViewUtil.showAlertDialog(this, R.string.ebei_logout, R.string.ebei_logout_remind, new CommonAlertDialogFragment.OnBtnClickListener() {
			@Override
			public void onClick(View v, CommonAlertDialogFragment dialog) {
				ViewUtil.dismissDialog(dialog);
				PublicUtil.doLogout(mContext);
			}
		}, null);
	}

	private void onClearCache() {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				String path = CommonUtil.getCacheFile(mContext);
				FileUtil.deleteFile(path);
				path = CommonUtil.getExternalCacheFile(mContext);
				FileUtil.deleteFile(path);
				return null;
			}

			protected void onPostExecute(Boolean result) {
				Toast.makeText(mContext, R.string.ebei_operate_success, Toast.LENGTH_SHORT).show();
				String cacheStr = "0MB";
				clearCacheView.setRightButtonTextView(cacheStr, null);
			};

		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void onBackupClicked(View v) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				return backupDatabase();
			}

			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(mContext, "导出成功", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(mContext, "导出失败", Toast.LENGTH_SHORT).show();
				}
			};

		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private boolean backupDatabase() {
		String databasePath = CommonUtil.getFile(mContext);
		File file = new File(databasePath);
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmm", Locale.CHINA);
		String version = VersionUtil.getVersionName(mContext);
		version = version.replace(".", "_");
		String databaseName = "data_" + sdf.format(new Date()) + "_" + version + ".zip";
		databasePath += "/" + databaseName;

		try {
			String packageName = null;
			try {
				PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
				packageName = info.packageName;
			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}
			if (StringUtil.isStringNullOrEmpty(packageName)) {
				return false;
			}
			String userAccount = SPManager.getInstance(this).get(SPConstants.USER_ACCOUNT, "");
			File newDb = new File(databasePath);
			File oldDb = new File("/data/data/" + packageName + "/databases/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db");
			if (newDb.exists()) {
				newDb.delete();
			}
			if (oldDb.exists()) {
				if (CommonConstants.IS_VERSION_DEV) {
					databasePath = CommonUtil.getExternalCacheFile(mContext) + "/" + userAccount + CommonDBHelper.DB_NAME_SUFFIX + ".db";
					newDb = new File(databasePath);
					InputStream streamFrom = new FileInputStream(oldDb);
					OutputStream streamTo = new FileOutputStream(newDb);
					byte buffer[] = new byte[1024];
					int len;
					while ((len = streamFrom.read(buffer)) > 0) {
						streamTo.write(buffer, 0, len);
					}
					streamFrom.close();
					streamTo.close();
					return true;
				}

				ZipFile zFile = new ZipFile(newDb);
				zFile.setFileNameCharset("UTF-8"); // 设置文件名编码，在UTF-8系统中需要设置

				ZipParameters parameters = new ZipParameters();
				parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
				parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
				parameters.setEncryptFiles(true);
				parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
				parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
				parameters.setPassword("Ebei_2015@tech");
				zFile.createZipFile(oldDb, parameters);
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}
